// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const _ = db.command

  // 获取前端传来的 username 参数
  const { manufacturerNam } = event
  console.log(manufacturerNam,22222)
  try {
    console.log(`Fetching orders for username: ${manufacturerNam}`)

    // 查询 Order 表中 username 字段等于传入的用户名的记录
    const ordersRes = await db.collection('Order')
      .where({
        user: manufacturerNam
      })
      .orderBy('orderCompleted', 'desc')  // orderCompleted 为 no 的排在前面
      .get()
    
    console.log(`Orders fetched successfully for username ${manufacturerNam}:`, ordersRes.data)

    const orders = ordersRes.data;
    const today = new Date();

    // 计算 expectDeliTime 与当前日期的天数差异，并添加到订单数据中
    orders.forEach(order => {
      const expectDeliTime = new Date(order.expectDeliTime);
      const timeDiff = expectDeliTime - today;
      const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 计算天数差异
      order.dayDiff = dayDiff;
    });

    // 按照 orderCompleted 和 天数差异升序排序
    orders.sort((a, b) => {
      if (a.orderCompleted === b.orderCompleted) {
        return a.dayDiff - b.dayDiff;
      }
      return a.orderCompleted === 'no' ? -1 : 1;
    });

    // 返回排序后的查询结果
    return {
      success: true,
      data: orders
    }
  } catch (error) {
    console.error('Error occurred:', error.message)
    // 返回错误结果
    return {
      success: false,
      message: 'Error: ' + error.message
    }
  }
} 
